package cn.edu.swu.ws.controller;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@WebServlet("/captcha")
public class CaptchaServlet extends HttpServlet {

    // 验证码字符集
    private static final String CHAR_SET = "ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789";
    private static final int WIDTH = 120;
    private static final int HEIGHT = 40;
    private static final int CODE_LENGTH = 4;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // 设置响应类型
        response.setContentType("image/jpeg");
        response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);

        // 创建图像
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = image.createGraphics();

        // 设置背景
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, WIDTH, HEIGHT);

        // 添加干扰线
        drawInterferenceLines(g);

        // 生成验证码
        String captchaCode = generateCaptchaCode();

        // 保存到session
        HttpSession session = request.getSession();
        session.setAttribute("captchaCode", captchaCode);
        session.setAttribute("captchaTime", System.currentTimeMillis());

        // 绘制验证码
        drawCaptchaCode(g, captchaCode);

        // 释放资源
        g.dispose();

        // 输出图像
        ImageIO.write(image, "JPEG", response.getOutputStream());
    }

    private String generateCaptchaCode() {
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < CODE_LENGTH; i++) {
            sb.append(CHAR_SET.charAt(random.nextInt(CHAR_SET.length())));
        }
        return sb.toString();
    }

    private void drawCaptchaCode(Graphics2D g, String code) {
        Random random = new Random();
        g.setFont(new Font("Arial", Font.BOLD, 24));

        for (int i = 0; i < code.length(); i++) {
            // 随机颜色
            g.setColor(new Color(
                    random.nextInt(128),
                    random.nextInt(128),
                    random.nextInt(128)
            ));

            // 随机旋转
            double angle = Math.toRadians(random.nextInt(30) - 15);
            g.rotate(angle, 25 + i * 25, 25);

            // 绘制字符
            g.drawString(String.valueOf(code.charAt(i)), 15 + i * 25, 28);

            // 恢复旋转
            g.rotate(-angle, 25 + i * 25, 25);
        }
    }

    private void drawInterferenceLines(Graphics2D g) {
        Random random = new Random();
        for (int i = 0; i < 6; i++) {
            g.setColor(new Color(
                    random.nextInt(200) + 55,
                    random.nextInt(200) + 55,
                    random.nextInt(200) + 55
            ));
            g.setStroke(new BasicStroke(1.5f));
            g.drawLine(
                    random.nextInt(WIDTH),
                    random.nextInt(HEIGHT),
                    random.nextInt(WIDTH),
                    random.nextInt(HEIGHT)
            );
        }

        // 添加噪点
        for (int i = 0; i < 50; i++) {
            int x = random.nextInt(WIDTH);
            int y = random.nextInt(HEIGHT);
            g.fillRect(x, y, 2, 2);
        }
    }
}